package com.tac.xiangmu3.common;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
@CrossOrigin
public class Interceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if(method.equalsIgnoreCase("options")){
            return true;
        }

        String token = response.getHeader("token");
        if(null!=token){
            JwtParser parser = Jwts.parser();
            parser.setSigningKey("tac666");
            try {
                Jws<Claims> claimsJws = parser.parseClaimsJws(token);
                return true;
            }catch (Exception e){
                R<Object> r = R.error("请重新登录");
                doResponse(r,response);
                return false;
            }
        }
        R<Object> r = R.error("请先登录");
        doResponse(r,response);
        return false;
    }
    public void doResponse(R r,HttpServletResponse response) throws IOException {
        String toJSONString = JSON.toJSONString(r);
       response.setContentType("text/json;charset=utf-8");
       response.getWriter().write(toJSONString);
    }
}
